using System;
using System.Collections.Generic;
using CarlosAg.ExcelXmlWriter;
using System.Linq;
using System.Web.DynamicData;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.Expressions;

namespace NotAClue.Web.DynamicData
{
    public static class ExcelExtensions
    {
        /// <summary>
        /// Exports the specified grid view.
        /// From: http://justgeeks.blogspot.com/2011/03/export-to-excel-using-dynamic-data.html
        /// </summary>
        /// <param name="gridView">The grid view.</param>
        /// <remarks></remarks>
        public static void Export(this GridView gridView, Boolean showAllColumns = false)
        {
            // get table
            var table = gridView.GetMetaTable();

            // execute the query that was used to populate the GridView.
            IQueryable queryResults = table.GetQuery(table.CreateContext());

            // get query extender
            var queryExtenders = gridView.Page.FlattenChildren().OfType<QueryExtender>();
            var gridQueryExtender = queryExtenders.FirstOrDefault(qe => qe.TargetControlID == gridView.DataSourceID);
            if (gridQueryExtender != null)
            {
                // add in any filters that are applied via the QueryExtender as well 
                var queryExtenderExpressions = gridQueryExtender.Expressions;

                foreach (DataSourceExpression expr in queryExtenderExpressions)
                {
                    if (expr is DynamicFilterExpression || expr is CustomExpression)
                        queryResults = expr.GetQueryable(queryResults);

                    // add multicolumn search
                    if (expr is SearchExpression)
                    {
                        var srchExp = (SearchExpression)expr;
                        var searchExpression = new SearchExpression()
                        {
                            ComparisonType = srchExp.ComparisonType,
                            DataFields = srchExp.DataFields,
                            //DataSource = sexpr.DataSource,
                            SearchType = srchExp.SearchType
                        };

                        var textBoxId = ((ControlParameter)srchExp.Parameters[0]).ControlID;
                        var searchValue = gridView.Page.FindControlRecursive<TextBox>(textBoxId).Text;
                        if (!String.IsNullOrEmpty(searchValue))
                        {
                            searchExpression.Parameters.Add(new Parameter() { DefaultValue = searchValue });
                            queryResults = searchExpression.GetQueryable(queryResults);
                        }
                    }

                    // do sort based on GridView
                    if (expr is OrderByExpression)
                    {
                        queryResults = expr.GetQueryable(queryResults);
                    }
                }

                // do sort based on GridView
                if (!String.IsNullOrEmpty(gridView.SortExpression))
                {
                    var orderByExpression = new OrderByExpression()
                        {
                            DataField = gridView.SortExpression,
                            Direction = gridView.SortDirection
                        };
                    queryResults = orderByExpression.GetQueryable(queryResults);
                }
            }

            var workbook = new Workbook();
            var sheet = workbook.Worksheets.Add("Sheet 1");
            var excel = new PopulateExcelWorksheetForDynamicData(sheet);
            if (queryResults != null)
            {
                excel.Populate(queryResults, table, showAllColumns);
                PopulateExcelWorksheetForDynamicData.SetDefaultStyle(workbook);
                // don't use spaces as this will cause issues. You can also try .xls, but you will get an corruption warning in IE. 
                string filename = gridView.Page.Title.Replace(" ", "-") + "-Export.xml";
                PopulateExcelWorksheetForDynamicData.SendToBrowserForDownload(workbook, filename, gridView.Page.Response);
            }
        }
    }
}
